package com.example.stars_project_android.index;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.stars_project_android.R;
import com.example.stars_project_android.entity.GuestBookEntity;
import com.example.stars_project_android.util.Constant;
import com.example.stars_project_android.util.PhotoUtils;
import com.google.android.material.internal.FlowLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 发布动态界面
 */
public class Postmessage extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {

    private Button cancel, post;   //取消和发布按钮
    private EditText message;   //发布的留言
    private ImageButton expression, label;  //表情和图片
    private ImageView img, img1, img2;
    protected ArrayList<String> addresses = new ArrayList<>();
    private static int TAKE_PHOTO = 1;
    public static int ALBUM_RESULT_CODE = 0x999 ;
    private List<Bitmap> imgList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_postmessage);
        //这一两行代码主要是向用户请求权限
        ActivityCompat.requestPermissions(Postmessage.this,
                new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
                },1);
        //这一两行代码主要是向用户请求权限
        if (ActivityCompat.checkSelfPermission(Postmessage.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(Postmessage.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }

        //绑定控件对象
        setView();
    }


    private void setView() {
        img = findViewById(R.id.img);
        img1 = findViewById(R.id.img1);
        img2 = findViewById(R.id.img2);
        cancel = findViewById(R.id.btn_post_delete);
        cancel.setOnClickListener(this);
        post = findViewById(R.id.btn_post);
        post.setOnClickListener(this);
        message = findViewById(R.id.et_post_message);
        expression = findViewById(R.id.ib_expression);
        expression.setOnClickListener(this);
        label = findViewById(R.id.ib_label);
        label.setOnClickListener(this);
    }

    /**
     * 重载onActivityResult方法，获取相应数据
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            //处理相机拍摄的图片
            if (requestCode == TAKE_PHOTO){
                Bundle bundle = data.getExtras();//在相机这个应用中包含的是整个二进制流
                Bitmap bitmap = (Bitmap) bundle.get("data");
                imgList.add(bitmap);
                if (img.getDrawable() != null) {
                    if (img1.getDrawable() != null){
                        img2.setImageBitmap(bitmap);
                    } else {
                        img1.setImageBitmap(bitmap);
                    }
                } else {
                    img.setImageBitmap(bitmap);
                }
            } else {
                //处理图库中的图片
                handleImageOnKitKat(data);
            }
        }
    }

    /**
     * 根据条件的不同去获取相册中图片的url
     * @param data
     */
    @TargetApi(value = 19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.example.stars_project_android".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.example.stars_project_android".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        Log.e("路径","图片");
        displayImage(imagePath);
        System.out.println(imagePath);
    }

    /**
     * 获取图片的路径
     * */
    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if(cursor != null){

            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    /**
     * 展示图片
     */
    private void displayImage(String imagePath) {
        Bitmap bitmap1 = BitmapFactory.decodeFile(imagePath);
        imgList.add(bitmap1);
        Log.e("展示","图片");
        if (img.getDrawable() != null) {
            if (img1.getDrawable() != null){
                img2.setImageBitmap(bitmap1);
            } else {
                img1.setImageBitmap(bitmap1);
            }
        } else {
            img.setImageBitmap(bitmap1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_post_delete:
                //跳转到留言板
                Intent intent = new Intent(this, Index.class);
                intent.putExtra("index",1);
                startActivity(intent);
                break;
            case R.id.btn_post:
                //发布留言,存储到数据库
                setData();
                Intent intent1 = new Intent(this, Index.class);
                intent1.putExtra("index",1);
                startActivity(intent1);
                break;
            case R.id.ib_expression:
                //表情
                break;
            case R.id.ib_label:
                //点击上传图片
                showPopueWindow();
                break;
            default:
                break;
        }
    }

    /**
     * 弹出popueWindow的方法
     */
    private void showPopueWindow(){
        View popView = View.inflate(this,R.layout.activity_popup,null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels*1/3;

        final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
//        popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //图库选择
//                openGallery();
                openSysAlbum();
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //相机拍摄
//                takephoto();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,TAKE_PHOTO);
                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);

    }

    /**
     * 打开系统相册
     * 定义Intent跳转到特定图库的Uri下挑选，然后将挑选结果返回给Activity
     * */
    private void openSysAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, ALBUM_RESULT_CODE);
    }

    /**
     * 处理发布的留言
     */
    private void setData() {
        GuestBookEntity guestBook = new GuestBookEntity();
        guestBook.setUserImg(R.mipmap.user_img1);
        guestBook.setUserId(Constant.starName);
        guestBook.setImg(imgList);
        guestBook.setUserMessage(message.getText().toString());
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        guestBook.setMessageTime(date);
        guestBook.setLikeNum("0");
        Constant.guestBookList.add(0,guestBook);
//        Constant.guestBookList.add(guestBook);
    }

    /**
     * 长按删除未实现
     * @param view
     * @return
     */
    @Override
    public boolean onLongClick(final View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("删除");
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String tag = (String) view.getTag();
                addresses.remove(tag);
            }
        });
        builder.create().show();
        return true;
    }
}